# @Time : 2024-11-06 17:56
# @Author : Fioman 
# @Phone : 13149920693
"""
as_completed(fs) 接收一个Future对象的迭代器,当这些Future对象中的某个任务完成时,迭代器生成该
Future对象.
as_completed()提供了一种方式来按照任务完成的顺序处理结果,而不是按照提交的顺序.它会阻塞等待至少一个
任务完成,然后返回该任务的Future对象.
"""
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed


def task_sleep(n):
    currentName = threading.current_thread().name
    print(f"{currentName} 开始")
    time.sleep(n)
    print(f"{currentName} 结束")
    return f"{currentName} 返回结果"


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=5, thread_name_prefix="task_") as executor:
        futures = [executor.submit(task_sleep, i) for i in range(10, 0, -1)]

        results = []
        for future in as_completed(futures):
            results.append(future.result())

    print("results = {}".format(results))
